package com.hrb.douban.activtity.setting;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hrb.douban.R;
import com.hrb.douban.mview.CustomTitleBar;
import com.hrb.douban.socket.HandShakeBean;
import com.hrb.douban.socket.MsgDataBean;
import com.hrb.douban.socket.PulseBean;
import com.hrb.douban.socket.RedirectException;
import com.hrb.douban.utils.ToastUtil;
import com.xuhao.didi.core.iocore.interfaces.IPulseSendable;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.socket.client.impl.client.action.ActionDispatcher;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;
import com.xuhao.didi.socket.common.interfaces.utils.TextUtils;

import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;


public class SocketActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.custom_title_bar)
    CustomTitleBar customTitleBar;
    @BindView(R.id.t1)
    TextView t1;
    @BindView(R.id.t2)
    EditText t2;
    @BindView(R.id.b1)
    Button b1;
    private ConnectionInfo mInfo;
    private IConnectionManager mManager;
    private SocketActionAdapter adapter = new SocketActionAdapter() {
        @Override
        public void onSocketIOThreadStart(String action) {
            super.onSocketIOThreadStart(action);
        }

        @Override
        public void onSocketIOThreadShutdown(String action, Exception e) {
            super.onSocketIOThreadShutdown(action, e);
        }

        @Override
        public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
            if (e != null) {
                if (e instanceof RedirectException) {
                    ToastUtil.show("正在重定向连接(Redirect Connecting)...");
                    mManager.switchConnectionInfo(((RedirectException) e).redirectInfo);
                    mManager.connect();
                } else {
                    ToastUtil.show("异常断开(Disconnected with exception):" + e.getMessage());
                    Log.d("abc","异常断开(Disconnected with exception):" + e.getMessage());
                }
            } else {
                ToastUtil.show("正常断开(Disconnect Manually)");
            }
        }

        @Override
        public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
            ToastUtil.show("连接成功");
            mManager.send(new HandShakeBean());
            mManager.getPulseManager().setPulseSendable(new PulseBean()).pulse();
        }

        @Override
        public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
            ToastUtil.show("连接失败");
        }

        @Override
        public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
            String str = new String(data.getBodyBytes(), Charset.forName("utf-8"));
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            if (cmd == 54) {//登陆成功
                String handshake = jsonObject.get("handshake").getAsString();
                Log.d("abc","握手成功! 握手信息(Handshake Success):" + handshake + ". 开始心跳(Start Heartbeat)..");
            } else if (cmd == 57) {//切换,重定向.(暂时无法演示,如有疑问请咨询github)
                String ip = jsonObject.get("data").getAsString().split(":")[0];
                int port = Integer.parseInt(jsonObject.get("data").getAsString().split(":")[1]);
                ConnectionInfo redirectInfo = new ConnectionInfo(ip, port);
                redirectInfo.setBackupInfo(mInfo.getBackupInfo());
                mManager.getReconnectionManager().addIgnoreException(RedirectException.class);
                mManager.disconnect(new RedirectException(redirectInfo));
            } else if (cmd == 14) {//心跳
                Log.d("abc","收到心跳,喂狗成功(Heartbeat Received,Feed the Dog)");
                mManager.getPulseManager().feed();
            } else {
                Log.d("abc",str);
                t1.setText(str);
            }
        }

        @Override
        public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
            byte[] bytes = data.parse();
            bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            switch (cmd) {
                case 54: {
                    String handshake = jsonObject.get("handshake").getAsString();
                    Log.d("abc","发送握手数据(Handshake Sending):" + handshake);
                    mManager.getPulseManager().pulse();
                    break;
                }
                default:
                    Log.d("abc",str);

            }
        }

        @Override
        public void onPulseSend(ConnectionInfo info, IPulseSendable data) {
            byte[] bytes = data.parse();
            bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            if (cmd == 14) {
                Log.d("abc","发送心跳包(Heartbeat Sending)");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);
        ButterKnife.bind(this);
        customTitleBar.getMtitle().setText(getIntent().getStringExtra("title"));
        customTitleBar.setTitleClickListener(this);
        b1.setOnClickListener(this);
        initData();
    }

    private void initData(){
        //mInfo=new ConnectionInfo("10.0.3.15",8080);
        mInfo=new ConnectionInfo("192.168.17.9",8080);
        final Handler handler =new Handler(Looper.getMainLooper());
        OkSocketOptions.Builder builder=new OkSocketOptions.Builder();
        builder.setReconnectionManager(OkSocketOptions.getDefault().getReconnectionManager());
        //builder.setReconnectionManager(new NoneReconnect());
        builder.setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
            @Override
            public void handleCallbackEvent(ActionDispatcher.ActionRunnable actionRunnable) {
                handler.post(actionRunnable);
            }
        });
        builder.setPulseFrequency(1000*10);
        mManager=OkSocket.open(mInfo).option(builder.build());
        mManager.registerReceiver(adapter);
        mManager.connect();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_left:
                finish();
                break;
            case R.id.b1:{
                if (mManager == null) {
                    return;
                }
                if (!mManager.isConnect()) {
                    ToastUtil.show("Unconnected");
                } else {
                    String msg = t2.getText().toString();
                    if (TextUtils.isEmpty(msg.trim())) {
                        return;
                    }
                    MsgDataBean msgDataBean = new MsgDataBean(msg);
                    mManager.send(msgDataBean);
                    t2.setText("");
                }
                break;
            }

        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mManager != null) {
            mManager.disconnect();
            mManager.unRegisterReceiver(adapter);
        }
    }




}
